<template>
	<div class="tab_bar">
		<ul class="flex scroll" ref='scroll'>
			<div class='slider' :style="{left:sliderOffset+'px'}"></div>
			<li v-for='item in catList' :key='item.id' :data-id='item.id' :class="{active:navIx==item.id}" @click="changeTab"  >
				{{item.name}}
			</li>
		</ul>
	</div>
</template>

<script>
export default {
		data() {
			return {
				sliderOffset: 12,
				id: '',
				width: '',
				navIx:201,	
			}
		},
		props:{
			catList:Array 
		},
		methods: {
			changeTab(e) {
				if(e.target.dataset.id != this.navIx) {
					this.sliderOffset = e.target.offsetLeft + 13;
					this.width =  e.target.innerText.length * 15;
					this.navIx = e.target.dataset.id;
					this.scroll();
					this.$emit('sliderClick',e.target.dataset.id)
				}	
			},
			scroll(type) {
				var scroll = this.$refs.scroll;
				var distance = this.sliderOffset - scroll.scrollLeft;
				var scrollWidth = 0; //可滚动的最大距离
				this.catList.forEach((item, index) => {
					scrollWidth = scrollWidth + item.name.length * 16 + 26;
				})
				scrollWidth = scrollWidth - scroll.clientWidth
				var rightPoint = 260; //右滚的位置
				var leftPoint = 80; //左滚的位置
				var maxTime = 20; //最大时间
				var speed = 7; //速度		{
				if(distance > rightPoint) {
					var i = 0;
					var moveRignt = () => {
						i++;
						scroll.scrollLeft = scroll.scrollLeft + speed;
						if(scroll.scrollLeft < scrollWidth && i < maxTime) {
							window.requestAnimationFrame(moveRignt);
						}
					}
					moveRignt();
				}
				if(distance < leftPoint) {   
					var j = 0;
					var moveLeft = () => {
						j++;
						scroll.scrollLeft = scroll.scrollLeft - speed;
						if(scroll.scrollLeft > 0 && j < maxTime) {
							window.requestAnimationFrame(moveLeft);
						}
					}
					moveLeft();
				}
		},
	}
}
</script>

<style scoped>
	* {
		padding: 0;
		margin: 0;
	}
	
	li {
		list-style: none;
	}
	/*导航栏*/
	.slider{width:32px;}
	.flex {
		display: flex;
	}
	
	.scroll::-webkit-scrollbar {
	    display: none;
    }
	
	.tab_bar ul {
		transition: 3s all;
		white-space: nowrap;
		position: relative;
		margin-right: 20px;
		-webkit-overflow-scrolling: touch;
		overflow: scroll;
		padding: 20px 0 0;
	}
	
	.tab_bar ul .slider {
		position: absolute;
		top: 90px;
		width:70px;
		height: 8px;
		transition: 0.5s left;
		background:linear-gradient(90deg,rgba(81,85,91,1) 0%,rgba(29,27,43,1) 100%);
		border-radius:4px 0px 4px 0px;
	}
	
	.tab_bar li {
		padding:20px 32px 40px;
		font-size:28px;
		color:#4A4A4A;
		font-family:'medi';
		font-weight:500;
	}
	
	.tab_bar .active {
		color: #333334;
		font-family:'semibold';
		font-weight:600;
	}
</style>